//
//  FlipsideViewController.m
//  SmartFlashlight
//
//  Created by Eric on 11/25/12.
//  Copyright (c) 2012 Saick. All rights reserved.
//

#import "MoreViewController.h"
#import "SQLibs.h"
#import "global_Header.h"
#import "UIView+RemoveView.h"
#import "TorchConfig.h"
#import "MoreDetailViewController.h"

@interface MoreViewController ()

@end

@implementation MoreViewController

- (void)dealloc
{
    [_table release];
    
    [super dealloc];
}

-(void)displayAllObject:(UIView*)aView indent:(NSInteger)aLayer
{
    NSLog(@"View:%@    -->%d", aView, aLayer);
    for (UIView *view in [aView subviews]) {
        [self displayAllObject:view indent:aLayer+1];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    [self setTitle:@"Flashlight Settings"];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackOpaque];
//    self.navigationController.navigationBar.tintColor = [UIColor redColor];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done:)] autorelease];
    
//    [self displayAllObject:self.navigationController.navigationBar indent:0];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.table reloadData];
    
    [MobClick beginLogPageView:@"MoreViewController"];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [MobClick endLogPageView:@"MoreViewController"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)shouldAutorotate
{
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark - Actions

- (IBAction)done:(id)sender
{
    [self.delegate moreViewControllerDidFinish:self];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
    /*
     0. power saving
        1> Auto Saving
        2> Stop using the Torch when battery level under 10% | 20%
     1. settings
        1> Flashlight turned on by default  (On)
        2> Stop auto-lock                   (On)
        3> Press anywhere to turn on        (On)
     2. contact us
     3. app prompt || remove id ? 
     */
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 2;
            break;
            
        case 1:
            return 3;
            break;
            
        case 2:
            if (kOSVersion >= 6.0f)
                return 3;
            else
                return 2;
            break;
            
        default:
            return 3;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"identifier_flip_about";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    [cell removeSubviews:[UISwitch class]];
    
    if (indexPath.section == 2) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        
        if (indexPath.row == 0)
            cell.textLabel.text = @"Contact us";
        else if (indexPath.row == 1)
            cell.textLabel.text = @"Developer's blog";
        else if (indexPath.row == 2)
            cell.textLabel.text = @"Like this app";
        else if (indexPath.row == 3)
            cell.textLabel.text = @"Share Flashlight with friends";
    } else {
        if (indexPath.section == 0 && indexPath.row == 1) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            cell.textLabel.text = [NSString stringWithFormat:@"Stop Using Torch                 %.0f%%", [TorchConfig sharedConfig].fStopTorch*100];
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            UISwitch *sw = [[UISwitch alloc] init];
            sw.center = CGPointMake(cell.center.x + 103.0f, (cell.bounds.size.height - sw.bounds.size.height)/2 + 13.0f);
            [cell addSubview:sw];
            
            [sw addTarget:self action:@selector(switchDidChangeValue:) forControlEvents:UIControlEventValueChanged];
            
            [sw release];
            
            switch (indexPath.row) {
                case 0:
                    if (indexPath.section == 0) {
                        cell.textLabel.text = @"Saving Automatic";
                        sw.on = [TorchConfig sharedConfig].isSavingAutomatic;
                    } else {
                        cell.textLabel.text = @"Disable Auto-Lock";
                        sw.on = [TorchConfig sharedConfig].isDisableAutoLock;
                    }
                    break;
                    
                case 1:
                    cell.textLabel.text = @"Default Turn On Torch";
                    sw.on = [TorchConfig sharedConfig].isDefaultOn;
                    break;
                    
                case 2:
                    cell.textLabel.text = @"Fullscreen Control";
                    sw.on = [TorchConfig sharedConfig].isEnableFullScreenControl;
                    break;
                      
                default:
                    break;
            }
        }
    }
    
    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return @"Power Saving";
            break;
            
        case 1:
            return @"General";
            break;
            
        case 2:
            return @"About us";
            break;
            
        default:
            return @"";
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0 && indexPath.row == 1) {
        // show detail view
        MoreDetailViewController *vcDetail = [[MoreDetailViewController alloc] initWithStyle:UITableViewStyleGrouped];
        [self.navigationController pushViewController:vcDetail animated:YES];
        [vcDetail release];
        
        [MobClick event:@"StopUsingTorch" label:@"pushViewController->MoreDetailViewController"];
    }
    
    if (indexPath.section == 2) {
        switch (indexPath.row) {
            case 0:
                [self mailToMe];
                [MobClick event:@"ContactUS"];
                break;
                
            case 1:
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:kDeveloperBlog]];
                [MobClick event:@"DevelopsBlog"];
                break;
                
//            case 2:
//                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:kUserReview]];
//                [MobClick event:@"LikeThisApp"];
//                break;
                
            case 2:
                // share to your friends
            {
                NSArray *activityItems = @[@"I've been using PowerSaving Flashlight and thought you might like it. It can save you battery life and protect you battery. Try it now! https://itunes.apple.com/us/app/powersaving-flashlight/id635718524?ls=1&mt=8", [UIImage imageNamed:@"icon@2x"]];
            
                UIActivityViewController *activityController =
                [[[UIActivityViewController alloc] initWithActivityItems:activityItems
                                                  applicationActivities:@[]] autorelease];
                
                [self presentViewController:activityController
                                   animated:YES
                                 completion:nil];
                
                [MobClick event:@"ShareFlashLightWithFriends"];
            }
                break;
                
            default:
                break;
        }
    }
}

#pragma mark - mail

-(void)displayComposerSheet
{
    MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
    mailPicker.mailComposeDelegate = self;
    mailPicker.navigationBar.barStyle = UIBarStyleBlackOpaque;
    [mailPicker setSubject:@"PowerSaving Flashlight Feedback"];
    
    NSArray *toRecipients = [NSArray arrayWithObject:kDeveloperMail];
    //    NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com"];
    //    NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com", nil];
    [mailPicker setToRecipients:toRecipients];
    //    [mailPicker setCcRecipients:ccRecipients];
    //    [mailPicker setBccRecipients:bccRecipients];
    
    //    UIImage *addPic = [UIImage imageNamed: @"3.jpg"];
    //    NSData *imageData = UIImagePNGRepresentation(addPic);            // png
    //    [mailPicker addAttachmentData: imageData mimeType: @"" fileName: @"3.jpg"];
    
    NSString *emailBody = @"PowerSaving Flashlight Feedback:";
    [mailPicker setMessageBody:emailBody isHTML:YES];
    
    [self presentModalViewController: mailPicker animated:YES];
    [mailPicker release];
}

-(void)launchMailAppOnDevice
{
    NSString *recipients = [NSString stringWithFormat:@"mailto:%@?subject=%@", kDeveloperMail, @"PowerSaving Flashlight Feedback"];
    //@"mailto:first@example.com?cc=second@example.com,third@example.com&subject=my email!";
    NSString *body = [NSString stringWithFormat:@"&body=%@", @"PowerSaving Flashlight Feedback:"];
    
    NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
    email = [email stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
    
    [MobClick event:@"ContactUS" label:@"launchMailAppOnDevice"];
}

- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    // do nothing here
    NSString *strMsg = nil;
    
    switch (result) {
        case MFMailComposeResultCancelled:
            strMsg = @"Mail save canceled.";
            break;
        case MFMailComposeResultSaved:
            strMsg = @"Mail save success.";
            break;
        case MFMailComposeResultSent:
            strMsg = @"Mail send success.";
            break;
        case MFMailComposeResultFailed:
            strMsg = @"Mail send failed.";
            break;
        default:
            break;
    }
    
    [MobClick event:@"ContactUS" label:strMsg];
    [[SQAlertView defaultAlert] promptMessage:strMsg atDuration:2.0f atMode:MBProgressHUDModeCustomView];
    [[SQAlertView defaultAlert] setUserInteraction:YES];
    
    [self dismissModalViewControllerAnimated:YES];
}

- (void)mailToMe
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (mailClass != nil) {
        if ([mailClass canSendMail])
            [self displayComposerSheet];
        else
            [self launchMailAppOnDevice];
    } else {
        [self launchMailAppOnDevice];
    }
}

#pragma mark - actions

- (void)switchDidChangeValue:(UISwitch *)sw
{
    NSIndexPath *indexPath = [_table indexPathForCell:(UITableViewCell *)sw.superview];
    if (indexPath.section == 0 && indexPath.row == 0) {
        [TorchConfig sharedConfig].isSavingAutomatic = sw.on;
        [MobClick event:@"SavingAutomatic" acc:sw.on];
    } else if (indexPath.section == 1 && indexPath.row == 0) {
        [TorchConfig sharedConfig].isDisableAutoLock = sw.on;
        [MobClick event:@"DisableAutoLock" acc:sw.on];
    } else if (indexPath.section == 1 && indexPath.row == 1) {
        [TorchConfig sharedConfig].isDefaultOn = sw.on;
        [MobClick event:@"DefaultTurnOnTorch" acc:sw.on];
    } else if (indexPath.section == 1 && indexPath.row == 2) {
        [TorchConfig sharedConfig].isEnableFullScreenControl = sw.on;
        [MobClick event:@"FullscreenControl" acc:sw.on];
    }
    
    [[TorchConfig sharedConfig] writeCurrentToUserDefault];
    [[TorchConfig sharedConfig] updateSettingAffect];
}

@end
